# app/__init__.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_cors import CORS
from flask_bcrypt import Bcrypt
from config import Config
import sys # 导入 sys 用于获取可执行文件路径

# 初始化扩展 (此时还没有 app 实例)
# 确保这里的 db 实例是唯一的，并且被 models.py 导入
db = SQLAlchemy()
# --- 移动打印语句到这里 ---
print(f"[__init__.py global] Shared db instance created. ID: {id(db)}")
migrate = Migrate()
bcrypt = Bcrypt()
cors = CORS() # 在这里初始化 CORS

def create_app(config_class=Config):
    # 打印 Python 解释器路径，用于确认环境
    print(f"[create_app start] Python Executable: {sys.executable}")
    app = Flask(__name__)
    app.config.from_object(config_class)
    app_id = id(app) # 获取 app 实例的 ID 用于日志跟踪
    print(f"[create_app:{app_id}] Flask app instance created.")

    # 使用 app 实例来完成核心扩展的初始化
    print(f"[create_app:{app_id}] Attempting db.init_app(app)...")
    db.init_app(app)
    print(f"[create_app:{app_id}] db.init_app finished.")

    print(f"[create_app:{app_id}] Attempting migrate.init_app(app, db)...")
    migrate.init_app(app, db)
    print(f"[create_app:{app_id}] migrate.init_app finished.")

    print(f"[create_app:{app_id}] Attempting bcrypt.init_app(app)...")
    bcrypt.init_app(app)
    print(f"[create_app:{app_id}] bcrypt.init_app finished.")

    print(f"[create_app:{app_id}] Attempting cors.init_app(app)...")
    cors.init_app(app, resources={r"/api/*": {"origins": "*"}})
    print(f"[create_app:{app_id}] cors.init_app finished.")

    # --- 关键：模型导入调试 ---
    print(f"[create_app:{app_id}] --- Attempting to import models ---")
    try:
        from . import models
        print(f"[create_app:{app_id}] --- 'from . import models' executed SUCCESSFULLY ---")
        # 尝试访问模型类，并检查它们使用的 db 实例 ID
        # 注意: 访问 User.query... 需要在应用上下文中，这里可能尚未完全建立，
        # 但 migrate 命令通常会提供上下文。如果这里报错，说明上下文可能有问题。
        # 一个更安全的方式可能是在模型中添加一个类方法来获取 db 实例 ID，
        # 但我们先尝试直接访问。
        print(f"[create_app:{app_id}] --- Found User model? Type: {type(models.User)}")
        print(f"[create_app:{app_id}] --- Found Outcome model? Type: {type(models.Outcome)}")
        print(f"[create_app:{app_id}] --- Found OutcomeType model? Type: {type(models.OutcomeType)}")
        # 检查模型元数据绑定的 MetaData 对象所关联的 'db' 实例 (如果存在)
        # 注意：这部分访问可能比较深入且依赖内部结构，仅作调试参考
        models_db_id = "Unknown"
        if hasattr(models.User, 'metadata') and hasattr(models.User.metadata, 'info') and 'db' in models.User.metadata.info:
             models_db_id = id(models.User.metadata.info['db'])
        elif hasattr(models.db, '__dict__'): # 备用检查方式
             # 这可能不准确，只是看 models 模块引用的 db 是否是同一个
             if 'db' in models.__dict__:
                 models_db_id = id(models.db)

        print(f"[create_app:{app_id}] --- Models likely using db ID: {models_db_id} ---")
        print(f"[create_app:{app_id}] --- Compare with shared db ID created globally: {id(db)} ---") # 确认模型用的 db 和全局 db 是同一个
    except ImportError as e:
        print(f"[create_app:{app_id}] !!! FAILED to import models: {e} !!!")
    except AttributeError as e:
        print(f"[create_app:{app_id}] !!! Models possibly imported, but specific class/attribute not found: {e} !!!")
    except Exception as e: # 捕获其他可能的异常
        print(f"[create_app:{app_id}] !!! UNEXPECTED ERROR during model import/check: {e} !!!")
        import traceback
        traceback.print_exc() # 打印详细的异常栈
    print(f"[create_app:{app_id}] --- Finished attempting to import models ---")
    # --- 结束模型导入调试 ---

    # 注册蓝图 (路由)
    print(f"[create_app:{app_id}] Registering blueprints...")
    from app.routes.auth import bp as auth_bp
    app.register_blueprint(auth_bp, url_prefix='/api/auth')

    from app.routes.outcomes import bp as outcomes_bp
    app.register_blueprint(outcomes_bp, url_prefix='/api/outcomes')

    from app.routes.users import bp as users_bp
    app.register_blueprint(users_bp, url_prefix='/api/users')

    from app.routes.types import bp as types_bp
    app.register_blueprint(types_bp, url_prefix='/api/outcome-types')
    print(f"[create_app:{app_id}] Blueprints registered.")

    # 一个简单的测试路由
    @app.route('/hello')
    def hello():
        return "后端服务正在运行!"

    print(f"[create_app:{app_id}] Returning app instance.")
    return app

